const User = require('../models/user')
const jsonwebtoken = require('jsonwebtoken')
const { tokenConfig } = require('../config/index')
const { genPassword } = require('../utils/cryp')
const { avatarType } = require('../config/setting')
const { strVerifyFn } = require('../utils/strVerify')
const { imgVerifyFn } = require('../utils/imgVerify')
const path = require('path')

class UserCtl {
  async findList(ctx) {
    let { name = '', page = 1, perPage = 15 } = ctx.query
    page = Math.max(page * 1, 1) - 1
    perPage = Math.max(perPage * 1, 1)
    const reg = new RegExp(name, 'ig')
    ctx.body = await User.find({
      name: reg
    }).limit(perPage).skip(perPage * page)
  }
  async findById(ctx) {
    const { fields = '' } = ctx.query
    const id = ctx.params.id
    const selectFields = fields.split(';').filter(f => f).map(f => ' +' + f).join('')
    const option = await User.findById(id)
      .select(selectFields)
    ctx.body = option
  }
  async login(ctx) {
    ctx.verifyParams({
      username: { type: 'string', required: true },
      password: { type: 'string', required: true },
    })
    const { username, password } = ctx.request.body
    const user = await User.findOne({
      username,
      password
    })
    if (!user) {
      ctx.throw(401, '用户名或密码错误')
    } else {
      const { _id, username } = user
      const token = jsonwebtoken.sign(
        { _id, username },
        tokenConfig.secret,
        { expiresIn: tokenConfig.expiresIn }
      )
      ctx.body = { token }
    }
  }
  async create(ctx) {
    ctx.verifyParams({
      username: { type: 'string', required: true },
      password: { type: 'string', required: true },
    })
    // ctx.request.files.file
    const { username, password } = ctx.request.body
    const repeatedUser = await User.findOne({ username })
    if (repeatedUser) {
      ctx.throw(409, '该用户名已注册')
    } else {
      // if (ctx.request.files.file) {
      //   var file = ctx.request.files.file
      //   var paths = path.join(__dirname, '../public/uploads', '/user/avatar')
      //   var avatar = imgVerifyFn(ctx, paths, avatarType, file)
      // }
      await new User({ username, password }).save()
      ctx.body = {
        username
      }
    }
  }
  async update(ctx) { // 用户信息更新
    ctx.verifyParams({
      name: { type: 'string', required: true }
    })
    await ctx.state.user.update(ctx.request.body)
    ctx.body = ctx.state.user
  }
  async uploadAvatar(ctx) { //上传用户头像
    if (ctx.request.files.file) {
      const file = ctx.request.files.file
      const paths = path.join(__dirname, '../public/uploads', '/user/avatar')
      const url = imgVerifyFn(ctx, paths, avatarType, file)
      await ctx.state.user.update({ avatar: url })
      ctx.body = { url }
    } else {
      ctx.throw(415, '不能上传空图片')
    }
    
  }
  async checkUserExist(ctx, next) { //检查用户是否存在
    const id = ctx.params.id
    const user = await User.findById(id)
    if (user) {
      ctx.state.user = user
      await next()
    } else {
      ctx.throw(404, '该用户不存在')
    }
  }
  async md5Password(ctx, next) { //密码加密
    const { password, username } = ctx.request.body
    const data = [
      { name: '用户名', reg: /^[a-z0-9]{8,12}$/, value:username },
      { name: '密码', reg: /^[a-zA-Z0-9]{8,12}$/, value: password }
    ]
    if (ctx.url === '/api/user') {
      const tf = strVerifyFn(data)
      if (!tf[0]) {
        ctx.throw(415, tf[1])
      }
    }
    ctx.request.body.password = genPassword(password)
    await next()
  }
  async checkOwner(ctx, next) { //判断登录用户和上传用户
    if (ctx.state.user._id === ctx.params.id) {
      await next()
    } else {
      ctx.throw(403, '亲，您没有权限！')
    }
  }
  async delete(ctx) {
    const id = ctx.params.id
    await User.findByIdAndRemove(id)
    ctx.status = 204
  }
}

module.exports = new UserCtl